LIBRARY IEEE;
USE IEEE.std_logic_1164.ALL;
USE IEEE.std_logic_unsigned.ALL;
USE IEEE.std_logic_arith.ALL;

ENTITY Count IS
    PORT (
        -- CLOCK signal
        CLK : IN STD_LOGIC;
        -- RESET signal
        RST : IN STD_LOGIC;
        -- CARRY flag
        CARRY : OUT STD_LOGIC
    );
END Count;

ARCHITECTURE CountArch OF Count IS

    COMPONENT FDivider IS
        PORT (
            -- CLOCK signal
            CLK : IN STD_LOGIC;
            -- Divided CLOCK signal
            DCLK : OUT STD_LOGIC;
            -- RESET signal
            RST : IN STD_LOGIC
        );
    END COMPONENT;

    SIGNAL DCLK : STD_LOGIC;
    SIGNAL count : STD_LOGIC_VECTOR(6 DOWNTO 0);
    SIGNAL carry_bit : STD_LOGIC := '0';

BEGIN
    -- map the divider
    U_FDivider : FDivider PORT MAP(CLK => CLK, RST => RST, DCLK => DCLK);

    CARRY <= carry_bit;

    count_pro : PROCESS (DCLK, RST)
    BEGIN
        IF (RST = '0') THEN
            -- asynchronous reset signal count, as soon as RST comes
            count <= "1010000";
        ELSIF (DCLK'event AND DCLK = '1') THEN
            -- when the positive edge of CLK arrives
            IF (count(3 DOWNTO 0) = "0000") THEN
                -- when ones place equals to "0000" aka.0
                IF (count >= "0000000") THEN
                    -- when count is more or equal than 0H (Hexadecimal)
                    IF (count = "0000000") THEN
                        -- when it comes to 0H (Hexadecimal)
                        -- carry bit turn 1
                        carry_bit <= '1';
                        count <= "1100000";
                    ELSE
                        -- not decrease to 0H (Correction by decreasing 6)
                        count <= count - 7;
                    END IF;
                ELSE
                    -- when count < 0H
                    count <= "1100000";
                END IF;
            ELSIF (count > "0000000") THEN
                -- count decrease
                count <= count - 1;
                -- clear carry bit
                carry_bit <= '0';
            ELSE
                -- when count <= 0
                count <= "1100000";
            END IF;
        END IF;
    END PROCESS; -- count

END CountArch; -- CountArch